import 'dart:convert';
import 'dart:typed_data';

import 'package:flutter/cupertino.dart';
// import 'package:flutter_admin/utils/helper/save_file_web.dart';
import 'package:flutter_admin/utils/helper/save_file_mobile.dart'
    if (dart.library.html) 'package:flutter_admin/utils/helper/save_file_web.dart';
import 'package:syncfusion_flutter_xlsio/xlsio.dart';

class SaleOfferFormExcel {
  static void generateExcel({String? fileName, List? data}) async {
    List<Map>? configure = [
      {
        'name': 'productName',
        'label': '产品名称',
        'columnWidth': 16.0,
      },
      {
        'name': 'description',
        'label': '型号',
        'columnWidth': 16.0,
      },
      {
        'name': 'quantity',
        'label': '数量',
        'columnWidth': 10.0,
      },
      {
        'name': 'unit',
        'label': '单位',
        'columnWidth': 10.0,
      },
      {
        'name': 'unitPrice',
        'label': '单价（元）',
        'columnWidth': 16.0,
      },
      {
        'name': 'sum',
        'label': '总价（元）',
        'columnWidth': 16.0,
      },
      {
        'name': 'comment',
        'label': '备注',
        'columnWidth': 16.0,
      },
    ];
    // Create a new Excel Document.
    final Workbook workbook = Workbook();

    // Accessing sheet via index.
    final Worksheet sheet = workbook.worksheets[0];
    sheet.enableSheetCalculations();

    sheet.getRangeByName('A1:G1').merge();
    // sheet.getRangeByIndex(1, 1).columnWidth = 80;
    sheet.getRangeByIndex(1, 1).rowHeight = 20;
    sheet.importList([fileName], 1, 1, false);
    sheet
        .getRangeByName('A' +
            (data!.length + 3).toString() +
            ':G' +
            (data.length + 3).toString())
        .merge();
    num sum = 0;
    for (var i = 0; i < data.length; i++) {
      sum += int.parse(data[i].toMap()['sum']);
    }
    sheet.getRangeByIndex(data.length + 3, 1).rowHeight = 20;
    // ignore: unnecessary_brace_in_string_interps
    sheet.importList(['合计：${sum}'], data.length + 3, 1, false);

    // 标题
    List titleList = [];
    for (var i = 0; i < configure.length; i++) {
      var title = configure[i];
      sheet.getRangeByIndex(2, i + 1).columnWidth = title["columnWidth"];
      sheet.getRangeByIndex(2, i + 1).rowHeight = 20;
      titleList.add(title["label"]);
    }

    // 添加标题
    sheet.importList(titleList, 2, 1, false);

    for (var i = 0; i < data.length; i++) {
      var text = data[i].toMap();
      // 正文
      var textList = [];
      for (var j = 0; j < configure.length; j++) {
        var title = configure[j];
        sheet.getRangeByIndex(i + 3, j + 1).columnWidth = title["columnWidth"];
        sheet.getRangeByIndex(i + 3, j + 1).rowHeight = 20;
        textList.add(text[title["name"]]);
      }
      // 添加正文
      sheet.importList(textList, 3 + i, 1, false);
    }

    //Import the Object list to Sheet
    // sheet.importList(list, 2, firstColumn, isVertical);
    //Defining a global style with properties.
    final Style globalStyle = workbook.styles.add('globalStyle');
    globalStyle.fontName = 'Times New Roman';
    globalStyle.fontSize = 14;
    globalStyle.backColorRgb = Color.fromARGB(128, 242, 242, 242);
    globalStyle.bold = true;
    globalStyle.wrapText = false;
    globalStyle.hAlign = HAlignType.center;
    globalStyle.vAlign = VAlignType.center;

    final Style globalStyle1 = workbook.styles.add('globalStyle1');
    globalStyle1.fontName = 'Times New Roman';
    globalStyle1.fontSize = 12;
    globalStyle1.wrapText = false;
    globalStyle1.hAlign = HAlignType.center;
    globalStyle1.vAlign = VAlignType.center;

    var char = intToASCII(96 + configure.length);
    sheet.getRangeByName('A1:A1').cellStyle = globalStyle;

    //Apply GlobalStyle
    sheet.getRangeByName('A2:' + char + '2').cellStyle = globalStyle;

    //Apply GlobalStyle1
    sheet
        .getRangeByName('A3:' + char + (data.length + 3).toString())
        .cellStyle = globalStyle1;
    // Save and dispose workbook.
    final List<int>? bytes = workbook.saveAsStream();
    workbook.dispose();
    // Download the output file in web.
    await FileSaveHelper.saveAndLaunchFile(bytes!, '$fileName.xlsx');
  }

  static dynamic intToASCII(int figure) {
    var listInt = [figure];
    var int2utf8 = Uint8List.fromList(listInt);
    return Utf8Codec().decode(int2utf8);
  }
}
